#! /usr/bin/env python3
#
#  Copyright 2022 Jimmy-Ge.Wang
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import os
import time
import numpy as np
import cv2
from playsound import playsound
import pyautogui

class Freshhema():
    def __init__(self):
        pass

    def refresh(self):
        os.system("adb shell input swipe 250 250 250 500")

    def capture_screen(self):
        os.system("adb shell screencap -p ./sdcard/Download/shopping_cart.png")
        os.system("adb pull ./sdcard/Download/shopping_cart.png")

    def is_order_available(self):
        img = cv2.imread('./shopping_cart.png')
        template = cv2.imread('./template.png')

        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

        result = cv2.matchTemplate(img_gray, template_gray, cv2.TM_CCOEFF_NORMED)
        threshold = 0.8
        loc = np.where(result >= threshold)
        if loc[0].size == 0:
            result = True
        else:
            result = False

        return result

if __name__ == '__main__':
    print("Freshhema notify app is started!")
    freshhema = Freshhema()
    message_sent = False

    while True:
        freshhema.refresh()
        time.sleep(1.5)
        freshhema.capture_screen()
        if freshhema.is_order_available():
            print('Order is available! Quick!!!')
            if not message_sent:
                pyautogui.typewrite('Hema Hema Hema Hema Hema Hema, quick!\n')
                pyautogui.typewrite('Hema Hema Hema Hema Hema Hema, quick!\n')
                pyautogui.typewrite('Hema Hema Hema Hema Hema Hema, quick!\n')
                playsound('triangle.mp3')
                message_sent = True
        else:
            message_sent = False
            print('Order is not available yet!')
